import React, { useState, KeyboardEvent, useCallback, useEffect } from 'react';
import { AutoComplete } from 'antd';
import debounce from 'lodash/debounce';


export default function AutoCompleteDemo({ xx }) {
  const [value, setValue] = useState<string>('');
  const [options, setOptions] = useState<{value: string}[]>([]); // 
  const [searchResult, setSearchResult] = useState<string>('there is no content');
  const [resultColor, setResultColor] = useState<string>('grey');

  const handleChange =(val: string) => {
    console.log('change', val)
    setValue(val);
    xx('父组件传递的方法', val)
  }
  // const handleSearch = (val: string) => {
  //   if (!val) {
  //     return;
  //   }
  //   console.log('onSearch', val);
  //   fetch(`http://localhost:8089/autoComplete?q=${val}`)
  //   .then((res) => {
  //       return res.json();
  //   }).then((data) => {
  //       console.log("onSearch response:", data);
  //       setOptions(data);
  //   }).catch((error) => {
  //       console.error("Error fetching data:", error);
  //   });
  // };

  // 这里handleSearch没有依赖外部变量，所以不需要useCallback，像上面的写法，加上也没关系，如果有外部变量依赖，必须加上useCallback
  const handleSearch = useCallback( (val: string) => {
    if (!val) {
      return;
    }
    console.log('onSearch', val);
    fetch(`http://localhost:8089/autoComplete?q=${val}`)
    .then((res) => {
        return res.json();
    }).then((data) => {
        console.log("onSearch response:", data);
        setOptions(data);
    }).catch((error) => {
        console.error("Error fetching data:", error);
    });
  }, []);

  // 防抖动处理, 防止输入过快
  // 使用useCallback来记住防抖函数，避免每次渲染都创建新的防抖函数
  // eslint-disable-next-line
  const debouncedHandleSearch = useCallback(debounce(handleSearch, 200), [handleSearch]);
  
  const handleSelect = (val: string) => {
    console.log('onSelect', val);

    const response = fetch(`http://localhost:8089/search?sellerName=${val}`);
    Promise.resolve(response).then((res) => {
      return res.json();
    }).then((data) => {
        console.log("onSelect response:", data);
        setSearchResult(data.result);
        setResultColor(data.status === 'success' ? 'green' : 'red');
    }).catch((error) => {
        console.error("Error fetching data:", error);
    });
  }

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      console.log("enter key:", value);
      const response = fetch(`http://localhost:8089/search?sellerName=${value}`);
      Promise.resolve(response).then((res) => {
          return res.json();
      }).then((data) => {
          console.log("handleKeyDown response:", data);
          setSearchResult(data.result);
          setResultColor(data.status === 'success' ? 'green' : 'red');
      }).catch((error) => {
          console.error("Error fetching data:", error);
      });
    }
  };

  // 卸载函数时，清除防抖函数的定时器
  useEffect(() => {
    const cancelDebounce = debouncedHandleSearch.cancel;
    return () => cancelDebounce();  
  }, [debouncedHandleSearch]);

  return (
    <div>
      AutoComplete(支持回车键)
      <AutoComplete
        style={{ width: 200 }}
        allowClear
        value={value}
        options={options}
        onChange={handleChange}
        onSearch={debouncedHandleSearch} // 输入内容时触发，一直输入一直触发 sdfdsdf
        onSelect={handleSelect}
        placeholder="增强版AutoComplete"
        onKeyDown={(event: KeyboardEvent<HTMLInputElement>) => handleKeyDown(event)}
      />
      <br />
      <div style={{ border: 'dashed', position: 'relative', textAlign: 'center', alignContent: 'center', 
           width: 600, height: 100, color: resultColor }}>
        {searchResult}
      </div>
    </div>
  );
}
